package com.yunban.project.api.text_check.service.impl;

import com.alibaba.fastjson2.JSON;
import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.domain.CorrectionDict;
import com.yunban.project.api.text_check.service.CorrectionDictService;
import com.yunban.project.api.text_check.service.CorrectionService;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: lijiajun
 * @date: 2024-11-21
 * @version: 1.0
 */
@Slf4j
@Primary
@Service("localCorrectionService")
public class LocalCorrectionServiceImpl implements CorrectionService {

    @Resource
    private CorrectionDictService correctionDictService;

    @Override
    public String correction(String text, CorrectionConfig config, String taskId) {
        // 获取已经开启的纠错词典
        List<CorrectionDict> list = this.correctionDictService.list();
        List<CorrectionDict> dictList = new ArrayList<>();
        for (CorrectionDict dict : list) {
            if (dict.isEnabled()) {
                dictList.add(dict);
            }
        }

        // 用于存储替换信息
        List<ReplacementInfo> replacementInfos = new ArrayList<>();
        // TODO 2024-11-28 这个地方的代码写的太傻了，因为需要最后返回给前端这个纠错来源是什么，现在这个代码结构只能在这个地方进行处理，所以导致这个代码傻傻的 ≧ ﹏ ≦
        // 找到所有错误词及其在文本中的位置
        for (CorrectionDict dict : dictList) {
            int index = text.indexOf(dict.getErrorWord());
            while (index != -1) {
                replacementInfos.add(new ReplacementInfo(index, index + dict.getErrorWord().length(), dict));
                index = text.indexOf(dict.getErrorWord(), index + 1);
            }
        }
        // 按照错误词在文本中的起始位置排序
        replacementInfos.sort(Comparator.comparingInt(ReplacementInfo::getStartIndex));
        log.info("替换信息：{}", JSON.toJSONString(replacementInfos));
        // 用于存储使用的字典ID
        List<Long> dictIds = new ArrayList<>();
        for (ReplacementInfo replacementInfo : replacementInfos) {
            dictIds.add(replacementInfo.getDict().getId());
        }
        // 从后向前替换，以避免替换过程中影响后续的位置
        for (int i = replacementInfos.size() - 1; i >= 0; i--) {
            ReplacementInfo info = replacementInfos.get(i);
            String correctedText = text.substring(0, info.getStartIndex()) + info.getDict().getCorrectWord() + text.substring(info.getEndIndex());
            log.info("替换词：{} -> {}，文本：{}，词典：{}", info.getDict().getErrorWord(), info.getDict().getCorrectWord(), correctedText, info.getDict().getId());
            text = correctedText;
        }

        // 将 dictIds 转换为字符串
        String dictIdStr = dictIds.stream().map(Object::toString).collect(Collectors.joining(","));
        return text + "-----" + dictIdStr;
    }

    @Data
    @AllArgsConstructor
    private static class ReplacementInfo {
        private int startIndex;
        private int endIndex;
        private CorrectionDict dict;
    }
}
